﻿using DemoWebApi.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace DemoWebApi.Controllers
{
    public class PersonController : ApiController
    {
        static List<PersonModel> personList = new List<PersonModel>()
        {
            new PersonModel() {  Name="鲁迅认识的那只猹", Gender="男", Address="来自星星", IdNumber="123"},
            new PersonModel() {  Name="路人甲", Gender="男", Address="Earth", IdNumber="124"},
            new PersonModel() {  Name="吃瓜群众", Gender="男", Address="Sky", IdNumber="125"},
        };

        /// <summary>
        /// 获取全部的Person
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IEnumerable<PersonModel> GetPersons()
        {
            return personList;
        }

        /// <summary>
        /// 根据IdNumber查找学生
        /// </summary>
        /// <param name="idNumber"></param>
        /// <returns></returns>
        [HttpGet]
        public PersonModel GetPersonByIdNumber(string idNumber)
        {
            return personList.Find(t => t.IdNumber == idNumber);
        }

        /// <summary>
        /// 添加一个 person
        /// </summary>
        /// <param name="person"></param>
        [HttpPost]
        public void AddPerson([FromBody]PersonModel person)
        {
            personList.Add(person);
        }


        /// <summary>
        /// 更新 指定idNumber 的person对象
        /// </summary>
        /// <param name="idNumber"></param>
        /// <param name="person"></param>
        [HttpPut]
        public void UpdatePersonByIdNumber([FromUri]string idNumber, [FromBody]PersonModel person)
        {
            PersonModel tempPerson = personList.Find(t => t.IdNumber == idNumber);
            if (tempPerson != null)
            {
                tempPerson.Name = person.Name;
                tempPerson.Address = person.Address;
                tempPerson.Gender = person.Gender;
            }
        }


        /// <summary>
        /// 根据idNumber 删除对象
        /// </summary>
        /// <param name="idNumber"></param>
        [HttpDelete]
        public void DeletePersonByIdNumber(string idNumber)
        {
            personList.RemoveAll(t => t.IdNumber == idNumber);
        }
    }
}
